<template>
  <div id="map" class="map">
    <TyphoonInfo ref="typhoonInfo" :closeInfo="this.closeInfo" :typhoonData="typhoonData" :flag="flag" />
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import { Point, MultiLineString, LineString } from "ol/geom";
import { fromLonLat } from "ol/proj";
import { Fill, Circle, Style, Stroke } from "ol/style";
import XYZ from 'ol/source/XYZ';
import { defaults as defaultControls } from 'ol/control';
import { getCable, getLandingPoint, popList } from "@/api/map";
import { getDataCenterListNew } from "@/api/map/newMap"
import { resPdata1, resPdata2, resPdata3, resPdata4 } from "../json/mapJson";
import { forEach } from 'ol/geom/flat/segments';
import TyphoonInfo from "./typhoonInfo.vue";
import Overlay from "ol/Overlay";
export default {
  name: "HelloWorld",
  components: {
    TyphoonInfo,
  },
  data() {
    return {
      map: null,
      resPdata: [],
      popdata: [],
      centerdata: [],
      lastZoomPoint: null,
      lastZoomPoint2: null,
      lastZoomPoint3: null,
      typhoonData: {},
      tfInfoOverlay: null,
      flag: null,
      cableNumber: null
    };
  },

  mounted() {
    // console.log(localStorage.getItem('flag'));
    this.initMap();
    this.getMap();
    this.addOverlay();
  },
  methods: {
    // 初始化地图
    initMap() {
      this.map = new Map({
        layers: [
          new TileLayer({
            // 创建一个使用Open Street Map地图源的瓦片图层
            source: new XYZ({
              url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
              wrapX: false
            })
          }),
        ],
        target: "map",
        view: new View({
          zoom: 3.8, // 缩放
          // projection: 'EPSG:4326', // 坐标系
          // center: [100.990969, 36.635013], // 地图中心点
          center: [221.469170, 131.224361]
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false
        }),
      });

    },

    // 获取后台数据
    async getMap() {
      const { data } = await getLandingPoint()
      this.resPdata = data

      const data2 = await popList()
      this.popdata = data2.data
      // console.log(`output->`, this.popdata)

      const data3 = await getDataCenterListNew()
      this.centerdata = data3.data
      // console.log('this.centerdata', this.centerdata);

      this.drawTyphoonPath();
      this.beforeDraw();
      this.designClickOnMap();
      this.getPopList()
      this.getCenterListPoints()
      this.designCenterClickOnMap()
    },
    // 显示数据中心点
    getCenterListPoints() {
      let data = []
      for (var i = 0; i < this.centerdata.length; i++) {
        if (this.centerdata[i] && this.centerdata[i].longitude && this.centerdata[i].latitude) {
          let obj = {}
          obj['assetCount'] = this.centerdata[i].assetCount
          obj['availableAreas'] = this.centerdata[i].availableAreas
          obj['cloudServerCount'] = this.centerdata[i].cloudServerCount
          obj['country'] = this.centerdata[i].country
          obj['dataCenterName'] = this.centerdata[i].dataCenterName
          obj['ipCount'] = this.centerdata[i].ipCount
          obj['latitude'] = this.centerdata[i].latitude
          obj['location'] = this.centerdata[i].location
          obj['locationAbbreviate'] = this.centerdata[i].locationAbbreviate
          obj['locationFullNameEn'] = this.centerdata[i].locationFullNameEn
          obj['longitude'] = this.centerdata[i].longitude
          obj['type'] = this.centerdata[i].type
          obj['useAge'] = this.centerdata[i].useAge
          obj['yearOpened'] = this.centerdata[i].yearOpened
          obj['cloudConponentSort'] = JSON.parse(this.centerdata[i].cloudConponentSort)
          obj['cloudServerSort'] = JSON.parse(this.centerdata[i].cloudServerSort)
          obj['ipScale'] = JSON.parse(this.centerdata[i].ipScale)
          obj['ipSort'] = JSON.parse(this.centerdata[i].ipSort)
          obj['portSort'] = JSON.parse(this.centerdata[i].portSort)
          obj['protocolSort'] = JSON.parse(this.centerdata[i].protocolSort)
          obj['webAppSort'] = JSON.parse(this.centerdata[i].webAppSort)
          obj['webFrameSort'] = JSON.parse(this.centerdata[i].webFrameSort)
          obj['severSort'] = JSON.parse(this.centerdata[i].severSort)
          data.push(obj)
        }
      }
      let points = data;
      let features = [];
      // console.log('points', points);

      for (let i = 0; i < data.length; i++) {
        let position = [points[i].longitude, points[i].latitude];
        let positionArr = fromLonLat(position)
        // console.log('positionArr', positionArr);

        if (!isNaN(positionArr[0]) && !isNaN(positionArr[1])) {
          let featurePoint = new Feature({
            geometry: new Point(positionArr),
          });

          featurePoint.setStyle(
            new Style({
              image: new Circle({
                fill: new Fill({
                  color: "#00B0FF",
                }),
                radius: 6,
              }),
            })
          );
          // console.log('@@points', points[i]);
          featurePoint.set('pointDataCenter', points[i])
          features.push(featurePoint);
        }
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },

    designCenterClickOnMap() {
      let _this = this;
      this.map.on("click", function (ev) {
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height]
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(
          pix,
          function (feature) {
            return feature;
          }
        );
        if (feature && feature.get('pointDataCenter')) {
          // console.log(`output->feature.get('typhoonPoint')`, feature.get('pointData'))
          _this.map.getTargetElement().style.cursor = "pointer";
          _this.getipData(feature.get('pointDataCenter'));
        } else {
          // console.log("no feature");
          _this.map.getTargetElement().style.cursor = "";
          _this.$store.state.switch.showDetail = false;
          _this.$store.state.switch.showDetailTwo = false;
        }
      });
    },

    // 数据中心详情页赋值
    getipData(data) {
      this.$store.state.switch.showDetail = true; //控制详情页展开
      this.$store.state.rightDetails.detailOneData = data
    },

    async getPopList() {
      let data = []
      for (var i = 0; i < this.popdata.length; i++) {
        if (this.popdata[i] && this.popdata[i].longitude && this.popdata[i].latitude
          && this.popdata[i].longitude > 0 && this.popdata[i].latitude > 0
        ) {
          data.push(this.popdata[i]);
        }
      }

      let points = data;
      let features = [];

      for (let i = 0; i < data.length; i++) {
        let position = [parseFloat(points[i].longitude), parseFloat(points[i].latitude)];
        var po = fromLonLat(position)
        // console.log(po)
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position)),
        });

        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: "#5470c6",
              }),
              radius: 6,
            }),
          })
        );



        // console.log('@@points', points[i]);
        featurePoint.set('pointPopData', points[i])
        features.push(featurePoint);
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },
    async beforeDraw() {
      const { data, cableNum } = await getCable();
      this.cableNumber = cableNum
      data.forEach(item => {
        if (item['coordinates']) {
          JSON.parse(item['coordinates']).forEach((val, i) => {
            this.drawLine(val, item['color'], item)
          })
        }

      })
      // this.drawLine(JSON.parse(data[0]['coordinates'])[0],item['color'],item)

    },
    async drawLine(data, color, topData) {
      let points = data;
      let features = [];
      let positions = [];

      // 创建线样式
      let redDashedLineStyle = new Style({
        stroke: new Stroke({
          color: color, // 线条颜色设置为红色
          width: 1, // 线条宽度
          // lineDash: [2, 3], // 虚线的模式，这里设置为10像素的实线和10像素的空白交替出现
        }),
      });
      for (let i = 0; i < points.length; i++) {
        let position = points[i];
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position)),
        });
        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: color,
              }),
              radius: 1,
            }),
          })
        );
        if (i != points.length - 1) {
          let nextPosition = points[i + 1];
          positions.push([fromLonLat(position), fromLonLat(nextPosition)]);
        }
        features.push(featurePoint);
      }
      let featureLine = new Feature({
        geometry: new MultiLineString(positions),
      });

      featureLine.set("lineData", topData);
      featureLine.setStyle(redDashedLineStyle); // 应用样式到Feature
      features.push(featureLine);
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },
    // 显示点
    drawTyphoonPath() {
      // let data = this.resPdata.filter(obj =>{ obj != null && obj.longitude && obj.latitude && obj.longitude > 0 && obj.latitude > 0 }) 
      // console.log(data)
      let data = []
      for (var i = 0; i < this.resPdata.length; i++) {
        if (this.resPdata[i] && this.resPdata[i].longitude && this.resPdata[i].latitude
          && this.resPdata[i].longitude > 0 && this.resPdata[i].latitude > 0
        ) {
          data.push(this.resPdata[i]);
        }
      }

      let points = data;
      let features = [];

      for (let i = 0; i < data.length; i++) {
        let position = [points[i].longitude, points[i].latitude];
        var po = fromLonLat(position)
        // console.log(po)
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position)),
        });

        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: "pink",
              }),
              radius:6,
            }),
          })
        );

        // console.log('@@points', points[i]);
        featurePoint.set('pointData', points[i])
        features.push(featurePoint);
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },

    // 注册一个click事件
    designClickOnMap: function () {
      let _this = this;
      this.map.on("pointermove", function (ev) {
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height]
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(
          pix,
          function (feature) {
            return feature;
          }
        );
        if (feature) {
          if (feature.get('pointData')) {

            _this.map.getTargetElement().style.cursor = "pointer";
            feature.getStyle().getImage().setRadius(8);
            let point = feature.get("pointData");
            let position = [point.longitude, point.latitude];
            _this.lastZoomPoint = feature;
            _this.setOverlayPosition(position);
            _this.typhoonData = point;
          } else if (feature.get('lineData')) {
            _this.map.getTargetElement().style.cursor = "pointer";
            feature.getStyle().getStroke().setWidth(4);
            let point = feature.get("lineData");
            let position = ev.coordinate;
            _this.lastZoomPoint2 = feature;
            _this.setOverlayPosition2(position);
            _this.typhoonData = point;
          } else if (feature.get('pointPopData')) {
            _this.map.getTargetElement().style.cursor = "pointer";
            feature.getStyle().getImage().setRadius(8);
            let point = feature.get("pointPopData");
            let position = [parseFloat(point.longitude), parseFloat(point.latitude)];
            _this.lastZoomPoint3 = feature;
            _this.setOverlayPosition3(position);
            _this.typhoonData = point;
          }
          feature.changed();
        } else {
          _this.map.getTargetElement().style.cursor = "";
          _this.clearPointZoomStyle();
          _this.closeInfo();
          // _this.$store.state.switch.showDetail = false;
          // _this.$store.state.switch.showDetailTwo = false;
          this.flag = null
        }
      });
    },
    // 设置overlay position
    setOverlayPosition: function (position) {
      // console.log(`output->position`, position)
      let transferPosition = fromLonLat(position);
      // console.log(`output->position44444444`, transferPosition)

      this.flag = 1
      this.tfInfoOverlay.setPosition(transferPosition);
    },
    // 设置overlay position
    setOverlayPosition2: function (position) {
      this.flag = 2
      let transferPosition = position;
      this.tfInfoOverlay.setPosition(transferPosition);
    },

    // 设置overlay position
    setOverlayPosition3: function (position) {
      // console.log(`output->position22222`, position)

      this.flag = 3
      let transferPosition = fromLonLat(position);
      // console.log(`output->position33333`, transferPosition)

      this.tfInfoOverlay.setPosition(transferPosition);
    },

    // clearPoint Zoom Style
    clearPointZoomStyle: function () {
      let _this = this;
      if (_this.lastZoomPoint != null) {
        _this.lastZoomPoint.getStyle().getImage().setRadius(6);
        _this.lastZoomPoint.changed();
      }
      if (_this.lastZoomPoint2 != null) {
        _this.lastZoomPoint2.getStyle().getStroke().setWidth(1);
        _this.lastZoomPoint2.changed();
      }
      if (_this.lastZoomPoint3 != null) {
        _this.lastZoomPoint3.getStyle().getImage().setRadius(6);
        _this.lastZoomPoint3.changed();
      }
    },
    // 关闭窗口显示
    closeInfo: function () {
      this.tfInfoOverlay.setPosition(undefined);
      this.flag = null

    },

    // 添加弹框
    addOverlay: function () {
      var popup = new Overlay({
        element: this.$refs.typhoonInfo.$el,
        autoPan: true,
      });
      popup.setPosition(undefined);
      this.tfInfoOverlay = popup;
      this.map.addOverlay(popup);
    },
  },

};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>
